import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nft/api/API.dart';
import 'package:flutter_nft/provider/LoginProvider.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class RegisterTwo extends StatefulWidget {
  @override
  _RegisterTwoState createState() => _RegisterTwoState();
}

class _RegisterTwoState extends State<RegisterTwo> {
  bool isChecked = false;

  bool isColor = false;

  late TextEditingController _controller = TextEditingController();

  String wxlogincode = "";

  String wxloginUrl = "";

  getBannerList()async{
    var request = await new Dio().get(API.reqUrl+"/get/banner/list");
    setState(() {
      wxloginUrl = request.data["dataObj"][4]["bannerUrl"].toString();
    });
  }

  @override
  void initState() {
    getBannerList();
    // TODO: implement initState
    super.initState();
    _controller.addListener(() {
      print(_controller.value.text.toString());
      if (_controller.value.text.toString().length >= 11) {
        setState(() {
          isColor = true;
        });
      } else {
        setState(() {
          isColor = false;
        });
      }
    });
  }

  //第三方APP微信登录
  void loginWX() {
    print(isChecked);
    if(isChecked){
      //拉取用户信息
      print("微信登录");
      fluwx
          .sendWeChatAuth(scope: "snsapi_userinfo", state: "wechat_sdk_demo_test")
          .then((data) {
        setState(() {
          print("拉取微信用户信息：" + data.toString());
        });
      }).catchError((e) {
        print('weChatLogin  e  $e');
      });

      //监听获取返回值
      fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) async {
        print("监听中...;.");
        if (res is fluwx.WeChatAuthResponse) {
          int errCode = res.errCode;
          //MyLogUtil.d('微信登录返回值：ErrCode :$errCode  code:${res.code}');
          print('微信登录返回值     '+res.code.toString());
          setState(() {
            wxlogincode = res.code.toString();
          });
          if (errCode == 0) {
            //把微信登录返回的code传给后台，剩下的事就交给后台处理
            // _presenter.getWeChatAccessToken(code);
            print('用户同意授权成功');
            var results = await new Dio().get(API.reqUrl+"/api/login/code/"+wxlogincode);
            print(results);
            print(results.data["token"].toString());
            if(results.data["openId"].toString() != ""){

              if(results.data["flag"]){
                print("登录成功................");

                SharedPreferences prefs = await SharedPreferences.getInstance();
                //存入缓存
                String phone = results.data["telePhone"];
                bool isLogin = results.data["flag"];
                String openId = results.data["openId"];
                print(phone.toString());
                //String token = result.data["token"];
                await prefs.setString("phone",phone.toString());
                await prefs.setBool("isLogin", isLogin);
                await prefs.setString("openId", openId.toString());
                //String resultToken = (await prefs.setString("token",token)) as String;
                // print("存入缓存..的数据...");

                //print(resultToken);
                // //存入状态
                //context.read<LoginProvider>().setToken(token.toString());
                context.read<LoginProvider>().setUserName(phone.toString());
                context.read<LoginProvider>().setIsLogin(true);
                context.read<LoginProvider>().setOpenId(results.data["openId"].toString());
                BrnToast.show(
                  "登录成功..",
                  context,
                  // preIcon: Image.asset(
                  //   "assets/image/icon_toast_success.png",
                  //   width: 24,
                  //   height: 24,
                  // ),
                  duration: BrnDuration.short,
                );

                //登录成功
                Navigator.of(context).pushNamed("tabbar");
              }else{
                context.read<LoginProvider>().setOpenId(results.data["openId"].toString());
                Navigator.of(context).pushNamed("registertwo");
              }

            }else{
              BrnToast.show(
                "授权中..",
                context,
                // preIcon: Image.asset(
                //   "assets/image/icon_toast_success.png",
                //   width: 24,
                //   height: 24,
                // ),
                duration: BrnDuration.short,
              );
            }

          } else if (errCode == -4) {

            print('用户拒绝授权');
          } else if (errCode == -2) {

            print('用户取消授权');
          }
        }
      });
    }else{
      BrnToast.show(
        "请勾选隐私条款！！",
        context,
        // preIcon: Image.asset(
        //   "assets/image/icon_toast_success.png",
        //   width: 24,
        //   height: 24,
        // ),
        duration: BrnDuration.short,
      );
    }


  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(20),
      child: Container(
        alignment: Alignment.bottomLeft,
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        //color: Colors.lightGreen,
        child: Container(
          alignment: Alignment.bottomLeft,
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              SizedBox(
                height: 20,
              ),
              InkWell(
                onTap: () {
                  Navigator.of(context).pop();
                },
                child: Container(
                    alignment: Alignment.bottomLeft,
                    width: MediaQuery.of(context).size.width,
                    height: 30,
                    child: Icon(
                      Icons.close,
                      size: 35,
                      color: Colors.white,
                    )),
              ),
              SizedBox(
                height: 30,
              ),
              context.read<LoginProvider>().getOpenId().toString() == ""? Container(
                margin: EdgeInsets.only(left: 15),
                alignment: Alignment.bottomLeft,
                width: MediaQuery.of(context).size.width,
                height: 100,
                child: Column(
                  children: [
                    Text(
                      "登录我们",
                      style: TextStyle(
                          fontSize: 30,
                          color: Colors.white,
                          fontWeight: FontWeight.w600),
                    ),
                    Text(
                      "发现有趣",
                      style: TextStyle(
                          fontSize: 30,
                          color: Colors.white,
                          fontWeight: FontWeight.w600),
                    ),
                  ],
                ),
              ):
              Container(
                margin: EdgeInsets.only(left: 15),
                alignment: Alignment.bottomLeft,
                width: MediaQuery.of(context).size.width,
                height: 100,
                child: Column(
                  children: [
                    Text(
                      "绑定手机号",
                      style: TextStyle(
                          fontSize: 30,
                          color: Colors.white,
                          fontWeight: FontWeight.w600),
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: 40,
              ),
              Padding(
                padding: EdgeInsets.only(left: 20, right: 10),
                child: TextField(
                  controller: _controller,
                  decoration: InputDecoration(
                      hintText: "请输入手机号码", fillColor: Colors.white70),
                ),
              ),
              SizedBox(
                height: 6,
              ),
              Padding(
                padding: EdgeInsets.only(left: 20),
                child: Container(
                  alignment: Alignment.bottomLeft,
                  child: Text(
                    "未注册的手机号通过验证将自动注册",
                    style: TextStyle(color: Colors.white70, fontSize: 12),
                  ),
                ),
              ),
              // Container(
              //   width: 150,
              //   height: 25,
              //   alignment: Alignment.bottomLeft,
              //   decoration: BoxDecoration(
              //       borderRadius: BorderRadius.circular(15),
              //       color: Colors.white24),
              // ),
              SizedBox(
                height: 70,
              ),
              Padding(
                padding: EdgeInsets.only(left: 15),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Container(
                            width: 30,
                            height: 30,
                            alignment: Alignment.bottomLeft,
                            //color: Colors.white24,
                            child: InkWell(
                              onTap: () {
                                print("点击...");
                                if (isChecked) {
                                  setState(() {
                                    isChecked = false;
                                  });
                                } else {
                                  setState(() {
                                    isChecked = true;
                                  });
                                }
                              },
                              child: Container(
                                width: 30,
                                height: 30,
                                alignment: Alignment.center,
                                //color: Colors.teal,
                                child: Container(
                                  width: 16,
                                  height: 16,
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(16),
                                      color: isChecked
                                          ? Colors.green
                                          : Colors.black,
                                      border: Border.all(
                                          width: 1,
                                          color: isChecked
                                              ? Colors.black54
                                              : Colors.white70)),
                                  child: isChecked
                                      ? Text(
                                          "√",
                                          style: TextStyle(
                                              fontSize: 10,
                                              color: Colors.black),
                                        )
                                      : Text(""),
                                ),
                              ),
                            ),
                          ),
                          Text("已阅读并同意",
                              style: TextStyle(
                                  fontSize: 10, color: Colors.white70))
                        ],
                      ),
                    ),
                    Container(
                        alignment: Alignment.centerLeft,
                        width: 200,
                        height: 20,
                        //color: Colors.green,
                        child: Text(
                          "<<用户服务协议>> <<隐私权政策>>",
                          style: TextStyle(fontSize: 10),
                        )),
                  ],
                ),
              ),
              SizedBox(
                height: 10,
              ),
              InkWell(
                onTap: () {
                  print("跳转路由携带手机号");
                  if (isColor && isChecked) {
                    //发送验证码
                    new Dio().get(API.reqUrl +
                        "/api/code/" +
                        _controller.value.text.toString());
                    Navigator.of(context).pushNamed("registercode",
                        arguments: _controller.value.text.toString());
                  }
                },
                child: Container(
                  alignment: Alignment.center,
                  width: 280,
                  height: 40,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(40),
                      color: isColor && isChecked
                          ? Color.fromRGBO(240, 224, 190, 1)
                          : Color.fromRGBO(81, 79, 66, 1)),
                  child: Text(
                    "发送短信验证码",
                    style: TextStyle(color: Color.fromRGBO(35, 32, 28, 1)),
                  ),
                ),
              ),
              SizedBox(height: 25,),
              context.read<LoginProvider>().getOpenId().toString() == ""? InkWell(
                onTap: () {
                  //点击微信登录
                  print("点击微信登录...");
                  loginWX();
                },
                child: Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                      color: Colors.green,
                      borderRadius: BorderRadius.circular(40),
                  image: DecorationImage(image: NetworkImage(wxloginUrl.toString()),fit: BoxFit.fill)
                  ),

                ),
              ):Text(""),
              // Container 手写一个........
            ],
          ),
        ),
      ),
    );
  }
}
